package com.itheima.algorithm.recursion_multi;

import java.util.Arrays;

/**
 * @author: TylerZhong
 * @description: 递归求斐波那契第n项
 */
public class E01Fibonacci {

    /**
     * 使用 Memoization(记忆法，也称备忘录)改进
     * @param n
     * @return
     */
    public static int fibonacci(int n) {
        int[] cache = new int[n + 1];
        Arrays.fill(cache, -1);
        cache[0] = 0;
        cache[1] = 1;
        return f(n,cache);
    }

    private static int f(int n, int[] cache){
        if (cache[n] != -1) {
            return cache[n];
        }
        int x = f(n - 1, cache);
        int y = f(n - 2, cache);
        cache[n] = x + y;
        return cache[n];
    }

    public static void main(String[] args) {
        int fibonacci = fibonacci(8);
        System.out.println(fibonacci);
    }
}
